<?php

class PermitsController extends AppController {

    public $name = "Permits";
    public $uses = array('Permit', 'PermitAttachment', 'Users', 'AviationAuthority', 'DepartmentSupervisor', 'Handler');
    public $components = array('Pdf', 'Upload');
    public $helpers = array('Paginator');
    public $paginate = array('Permit' => array('order' => array('created_dt' => 'desc')));

    function beforeFilter() {
        if( $this->action != "admin_login" && $this->action != "admin_logout" ) {
            if( $this->Session->check('user') == false ) {
                $this->redirect('/admin/users/login/');
            }
        }
    }

    public function admin_index() {
        $permits = $this->Permit->getOpenPermits();
        $this->set('permits', $permits);
    }

    public function admin_add() {

        if( isset($_POST['data']) && !isset($_POST['permit_id']) ) {
            $this->autoRender = false;

            $user = $this->Session->read('user');

            if( isset($_POST['data']['id']) && $_POST['data']['id'] != "" ) {
                $_POST['data']['Permit']['modified_by'] = $user['User']['id'];
            } else {
                $_POST['data']['Permit']['created_by'] = $user['User']['id'];
                $_POST['data']['Permit']['created_dt'] = date('Y-m-d H:i:s');
            }
            debug($_POST['data']);
            $this->Permit->id = is_numeric($_POST['data']['Permit']['id']) ? $_POST['data']['Permit']['id'] : NULL;
            $this->Permit->saveAll($_POST['data']);
            $this->Permit->saveField("ref_no", "SBOC" . $this->Permit->id . "-" . date('y'));

            echo json_encode($_POST['data']);

            return;
        }

        if( isset($_POST['permit_id']) ) {

            $permit = $this->Permit->find('first', array(
                'contain' => array('PermitSchedule'),
                'conditions' => array('Permit.id' => $_POST['permit_id']))
            );

            $this->set('permit', $permit);
        }
    }

    public function admin_delete() {

        if( $this->RequestHandler->isAjax() ) {
            $this->autoRender = false;

            $user = $this->Session->read('user');
            $this->Permit->setStatus($_POST['permit_id'], 'deleted', $user['User']['id']);
        }
    }

    public function admin_delete_schedule($permit_schedule_id) {
        $this->autoRender = false;
        
        if( $this->RequestHandler->isAjax() ) {
            if( is_numeric($permit_schedule_id) ) {
                $this->Permit->PermitSchedule->id = $permit_schedule_id;
                $this->Permit->PermitSchedule->delete();
            }
        }
    }

    public function admin_details($id) {
        $permit = $this->Permit->find('first', array(
            'contain' => array(
                'PermitSchedule', 'Handler' => array('fields' => array('id', 'name')),
                'PermitStatus' => array(
                    'order' => array('id' => 'desc'),
                    'limit' => 1
                )
            ),
            'conditions' => array('Permit.id' => $id))
        );
        $this->set('permit', $permit);
    }

    public function admin_dashboard_details($id) {
        $permit = $this->Permit->find('first', array(
            'contain' => array(
                'PermitSchedule', 'Handler' => array('fields' => array('id', 'name')),
                'PermitStatus' => array(
                    'order' => array('id' => 'desc'),
                    'limit' => 1
                )
            ),
            'conditions' => array('Permit.id' => $id))
        );
        $this->set('permit', $permit);
    }

    public function admin_changeStatus() {

        if( $this->RequestHandler->isAjax() ) {

            if( isset($_POST['data']['Permit']) || isset($_POST['ids']) ) {
                $this->autoRender = false;

                $user = $this->Session->read('user');

                if( isset($_POST['data']['Permit']['id']) ) {
                    $this->Permit->setStatus($_POST['data']['Permit']['id'], $_POST['status'], $user['User']['id'], $_POST['comments']);
                } else if( isset($_POST['ids']) ) {
                    $ids = explode(",", $_POST['ids']);

                    foreach ($ids as $id) {
                        $this->Permit->setStatus($id, $_POST['status'], $user['User']['id'], $_POST['comments']);
                    }
                }

                echo json_encode(array('status' => $_POST['status'], 'open' => in_array($_POST['status'], $this->Permit->openStatuses())));

                return;
            }
        }

        if( !isset($_POST['permit_id']) && !isset($_POST['status']) ) {
            $this->autoRender = false;
            echo "Error. No Permit Number or New Status Specified";
            return;
        }


        $permit = $this->Permit->find('first', array(
            'conditions' => array('Permit.id' => $_POST['permit_id']),
            'recursive' => -1
                ));

        $this->set('permit', $permit);
        $this->set('status', $_POST['status']);
    }

    public function admin_list() {
        if( $this->RequestHandler->isAjax() ) {
            $this->autoLayout = false;

            $offset = isset($_GET['offset']) ? $_GET['offset'] : 0;
            $limit = 25;

            $this->set('pg_offset', $offset + 1);
            $this->set('pg_size', $limit);

            $this->paginate = array(
                'Permit' => array(
                    'fields' => $this->Permit->general_fields,
                    'contain' => array('PermitSchedule'),
                    'order' => array('id' => 'desc'),
                    'limit' => $limit,
                    'recursive' => -1
                )
            );

            // if we are searching for a permit
            if( isset($_GET['term']) && $_GET['filter'] != "" ) {

                /* if ($_GET['filter'] == "sb") {
                  $permit_search_term = "Permit.ref_no";
                  } elseif ($_GET['filter'] == "pr") {
                  $permit_search_term = "Permit.permit_number";
                  } elseif ($_GET['filter'] == "pt") {
                  $permit_search_term = "Permit.type";
                  } else if ($_GET['filter'] == "lc") {
                  $permit_search_term = "Permit.permit_location";
                  } else if ($_GET['filter'] == "cn") {
                  $permit_search_term = "Permit.company_name";
                  } else if ($_GET['filter'] == "st") {
                  $permit_search_term = "Permit.status";
                  } */

                $permit_search_term = $_GET['filter'];

                $permits = $this->paginate('Permit', array(
                    $permit_search_term . " LIKE" => "%" . $_GET['term'] . "%"
                        ));

                $this->set('permits', $permits);
                $this->set('status', 'open');
            } else if( $_GET['status'] == 'open' ) {

                $permits = $this->paginate('Permit', array('status' => $this->Permit->openStatuses()));

                $this->set('permits', $permits);
                $this->set('status', 'open');
            } else if( $_GET['status'] == 'cancelled' ) {

                $permits = $this->paginate('Permit', array('status' => 'canceled'));

                $this->set('permits', $permits);
                $this->set('status', 'cancelled');
            } else {
                $permits = $this->paginate('Permit', array('status' => 'closed'));

                $this->set('permits', $permits);
                $this->set('status', 'closed');
            }
        }
    }

    public function admin_dashboard_list() {
        if( $this->RequestHandler->isAjax() ) {
            $this->autoLayout = false;

            $offset = isset($_GET['offset']) ? $_GET['offset'] : 0;
            $limit = 30;

            $this->set('pg_offset', $offset + 1);
            $this->set('pg_size', $limit);

            $this->set('permits', $this->Permit->getOpenActivePermits($offset, $limit));
            $this->set('pages', ceil($this->Permit->getTotalOpen() / $limit));
            $this->set('status', 'open');
        }
    }

    public function admin_updatePermitInfo() {

        $this->autoLayout = false;

        if( $this->RequestHandler->isAjax() ) {
            if( !isset($_POST['data']) ) {
                $this->set('permit', $this->Permit->findById($_POST['permit_id']));
            } else {
                $this->autoRender = false;

                // the following might better be handled using statuses, but keeping for ease
                // of access within UI
                $permit = $this->Permit->find('first', array(
                    'conditions' => array('Permit.id' => $_POST['data']['Permit']['id']),
                    'recursive' => -1
                        ));

                /* if ($permit['Permit']['permit_receive_caa_date'] == "" ||
                  $permit['Permit']['permit_receive_caa_date'] == "0000-00-00 00:00:00") {

                  $_POST['data']['Permit']['permit_receive_caa_date'] = date('Y-m-d H:i:s');
                  } */
                // end addition

                $data = $this->Permit->save($_POST['data']);

                $user = $this->Session->read('user');

                $this->Permit->setStatus($_POST['data']['Permit']['id'], 'approved', $user['User']['id']);

                echo json_encode($data);
            }
        }
    }

    public function admin_cancelPermitRequest() {

        $this->autoRender = false;

        if( $this->RequestHandler->isAjax() ) {
            $user = $this->Session->read('user');
            $this->Permit->setStatus($_POST['permit_id'], 'canceled', $user['User']['id']);
        }
    }

    public function admin_closePermitRequest() {

        $this->autoRender = false;

        if( $this->RequestHandler->isAjax() ) {
            $user = $this->Session->read('user');
            $this->Permit->setStatus($_POST['permit_id'], 'closed', $user['User']['id']);
        }
    }

    public function admin_holdPermitRequest() {

        $this->autoRender = false;

        if( $this->RequestHandler->isAjax() ) {
            if( isset($_POST['permit_id']) ) {
                $user = $this->Session->read('user');
                $this->Permit->setStatus($_POST['permit_id'], 'on hold', $user['User']['id']);
            }
        }
    }

    public function admin_forwardingForm() {
        $this->autoLayout = false;

        $permit_id = isset($_POST['permit_id']) ? $_POST['permit_id'] : -1;

        if( $permit_id != -1 ) {
            $this->set('permit', $this->Permit->find('first', array(
                        'contain' => array('PermitSchedule'),
                        'conditions' => array('Permit.id' => $permit_id))
                    ));
        }

        if( !$this->RequestHandler->isAjax() ) {
            // generate header for file download
        }
    }

    public function admin_printForwardingForm($permit_id, $options = '') {

        if( $options == 'download' ) {
            $user = $this->Session->read('user');
            $permit = $this->Permit->find('first', array(
                'contain' => array('PermitSchedule'),
                'conditions' => array('Permit.id' => $permit_id))
            );
            $supervisor = ClassRegistry::init('DepartmentSupervisor')->getSupervisor($user);

            $this->Pdf->download("forwarding_form_{$permit['Permit']['ref_no']}.pdf", '/elements/permits/forwarding_form_content', array('permit' => $permit, 'supervisor' => $supervisor, 'staff' => $user));

            return;
        }

        $this->layout = "print_layout";

        $user = $this->Session->read('user');

        $supervisor = $this->DepartmentSupervisor->getSupervisor($user);

        $permit = $this->Permit->find('first', array(
            'contain' => array('PermitSchedule'),
            'conditions' => array('Permit.id' => $permit_id))
        );
        $title_for_layout = "Forwarding Form - " . $permit['Permit']['ref_no'];

        $this->set('permit', $permit);
        $this->set('staff', $this->Session->read('user'));
        $this->set('title_for_layout', $title_for_layout);
        $this->set('supervisor', $supervisor);
    }

    /**
     * Handles the generation of the UI for preparing the Request Form to be sent to Civil
     * Aviation Authorities.
     * 
     * @return type 
     */
    public function admin_requestForm() {

        if( $this->RequestHandler->isAjax() ) {

            if( isset($_POST['action']) && $_POST['action'] == "set_authority" ) {
                $this->autoRender = false;

                $user = $this->Session->read('user');
                $this->Permit->setAviationAuthority($_POST['permit_id'], $_POST['authority_id'], $user['User']['id'], $_POST['handler_id']);

                echo json_encode(array('permit_id' => $_POST['permit_id'], 'status' => 'caa'));
                return;
            }
        }

        $this->autoLayout = false;

        $authorities = $this->AviationAuthority->find('list', array(
            'fields' => array('id', 'name', 'country'),
            'order' => array('country', 'name'))
        );

        $handlers = $this->Handler->find('list', array(
            'fields' => array('id', 'name', 'country'),
            'order' => array('country', 'name')
                ));

        $this->set('authorities', $authorities);
        $this->set('handlers', $handlers);

        $permit_id = isset($_POST['permit_id']) ? $_POST['permit_id'] : -1;

        if( $permit_id != -1 ) {
            $permit = $this->Permit->find('first', array(
                'contain' => array(
                    'AviationAuthority',
                    'PermitStatus' => array(
                        'conditions' => array('status' => 'caa'),
                        'order' => array('id' => 'desc'),
                        'limit' => 1
                    ),
                    'PermitSchedule'
                ),
                'conditions' => array('Permit.id' => $permit_id))
            );

            $this->set('permit', $permit);
        }
    }

    /**
     * Generates the UI and initiates the printing process for the Permit Request
     * 
     * @param int $permit_id 
     */
    public function admin_printRequestForm($permit_id, $options = '') {

        if( $options == 'download' ) {
            $user = $this->Session->read('user');
            $permit = ClassRegistry::init('Permit')->getForRequestFormPrint($permit_id);
            $supervisor = ClassRegistry::init('DepartmentSupervisor')->getSupervisor($user);

            $this->Pdf->download("request_form_{$permit['Permit']['ref_no']}.pdf", '/elements/permits/request_form_content', array('permit' => $permit, 'supervisor' => $supervisor));

            return;
        }

        $this->layout = "print_layout";

        $user = $this->Session->read('user');

        $permit = $this->Permit->getForRequestFormPrint($permit_id);
        $supervisor = $this->DepartmentSupervisor->getSupervisor($user);

        $title_for_layout = "Permit Request Form - " . $permit['Permit']['ref_no'];

        $this->set('permit', $permit);
        $this->set('title_for_layout', $title_for_layout);
        $this->set('supervisor', $supervisor);
        $this->set('print_status', true);
    }

    /**
     * Generates the required UI for sending Permit Request Email with the attached
     * Request in PDF Format
     * 
     * @param int $permit_id 
     */
    public function admin_sendRequestForm($permit_id) {
        $permit = $this->Permit->getForRequestForm($permit_id);
        $this->set('permit', $permit);
    }

    /**
     * Generates the required UI for sending Permit Request Email with the attached
     * Request in PDF Format
     * 
     * @param int $permit_id 
     */
    public function admin_sendForwardingForm($permit_id) {
        $permit = $this->Permit->getForRequestForm($permit_id);
        $this->set('permit', $permit);
    }

    public function admin_addAttachment() {

        if( isset($_POST['data']) ) {
            $this->autoRender = false;

            $user = $this->Session->read('user');

            if( isset($_FILES['attachments']) ) {
                $attachments = $this->Upload->uploadFiles($_FILES['attachments']);
                $data = array();

                foreach ($attachments as $attachment) {
                    $att = array(
                        'permit_id' => $_POST['data']['PermitAttachment']['permit_id'],
                        'mime_type' => $attachment['mime_type'],
                        'file_name' => $attachment['file_name'],
                        'attachment' => $attachment['data']
                    );

                    if( isset($_POST['data']['PermitAttachment']['id']) ) {
                        $att['id'] = $_POST['data']['PermitAttachment']['id'];
                        $att['modified_by'] = $user['User']['id'];
                    } else {
                        $att['created_dt'] = date('Y-m-d H:i:s');
                        $att['created_by'] = $user['User']['id'];
                    }

                    $data[] = $att;
                }

                $this->PermitAttachment->saveAll($data);
            }

            return;
        }

        $permit_id = $_POST['permit_id'];

        $permit_attachments = $this->PermitAttachment->find('all', array(
            'fields' => array('id', 'file_name', 'created_dt'),
            'conditions' => array('PermitAttachment.permit_id' => $permit_id),
            'recursive' => -1
                ));

        $this->set('permit_id', $permit_id);
        $this->set('permit_attachments', $permit_attachments);
    }

    public function admin_deleteAttachment($permit_attachment_id) {
        $this->autoRender = false;

        $this->PermitAttachment->id = $permit_attachment_id;
        $this->PermitAttachment->delete();
    }

    public function admin_viewAttachment($permit_attachment_id) {
        $this->autoRender = false;

        $attachment = $this->PermitAttachment->find('first', array(
            'conditions' => array('PermitAttachment.id' => $permit_attachment_id),
            'recursive' => -1
                ));

        header("Content-type: " . $attachment['PermitAttachment']['mime_type']);
        header("Content-Disposition: inline; filename=\"" . $attachment['PermitAttachment']['file_name'] . "\"");

        echo $attachment['PermitAttachment']['attachment'];
    }

}

?>
